package extendobj

import (
	"encoding/json"
	"errors"
	"io/ioutil"
	"iot-base/common/crudextend"
	"iot-base/common/dbconn"
	"iot-base/common/logger"
	"iot-base/common/webapi"

	"github.com/gin-gonic/gin"
	"gorm.io/datatypes"
	"gorm.io/gorm"
)

type MObj struct {
	SName string         `gorm:"type:varchar(40);primaryKey" json:"s_name"`
	Body  datatypes.JSON `json:"body"`
}

func init() {
	dbconn.DBConnection.AutoMigrate(&MObj{})
}
func handle(c *gin.Context) {
	qmap := c.QueryMap("qmap")
	mid := c.Param("module")
	action := c.Request.Method
	var infos []map[string]interface{}
	var info map[string]interface{}
	body, err := ioutil.ReadAll(c.Request.Body)
	if body != nil && len(body) > 0 {
		err = json.Unmarshal(body, &info)
		if err != nil {
			err = json.Unmarshal(body, &infos)

		}
	}

	if err != nil {
		logger.SLog.Warn("____________get body error----------", err)
	}
	res := crudextend.GetHTTPResult(action, mid, qmap, info, infos)
	if res != nil {
		if res.Err != nil {
			webapi.SendError(res.Err.Error(), -4000, c)
		} else {
			if res.Infos != nil {
				webapi.SendResult(res.Infos, nil, c)
			} else if res.Info != nil {
				webapi.SendResult(res.Info, nil, c)
			} else {
				webapi.SendOK(c)
			}

		}
	} else {
		webapi.SendError("模块返回null", -4000, c)

	}

}

//InitAPI 初始化
func InitAPI(r *gin.RouterGroup) {
	eapi := r.Group("/extend/api")
	{
		eapi.GET("/:module", func(c *gin.Context) {
			handle(c)
		})
		eapi.POST("/:module", func(c *gin.Context) {
			handle(c)
		})
		eapi.PUT("/:module", func(c *gin.Context) {
			handle(c)
		})
		eapi.DELETE("/:module", func(c *gin.Context) {
			handle(c)
		})
	}
	//针对物模型的扩展可放入该表
	mobj := r.Group("/mobj")
	{
		mobj.GET("/:id", func(c *gin.Context) {
			id := c.Param("id")
			if id == "ALL" || id == "" {
				var objs []MObj
				err := dbconn.DBConnection.Find(&objs).Error
				webapi.SendResult(objs, err, c)

			} else {
				var obj MObj
				obj.SName = id
				err := dbconn.DBConnection.Find(&obj).Error
				webapi.SendResult(obj, err, c)
			}
		})
		mobj.PUT("/", func(c *gin.Context) {
			var obj MObj
			err := c.ShouldBind(&obj)
			if err == nil {
				err = dbconn.DBConnection.Transaction(func(tx *gorm.DB) error {
					tx.Delete(&obj)
					return tx.Create(&obj).Error
				})
				if err == nil {
					webapi.SendOK(c)
				} else {
					webapi.SendResult(nil, err, c)
				}
			} else {
				webapi.SendResult(nil, err, c)
			}

		})
		mobj.DELETE("/:id", func(c *gin.Context) {
			id := c.Param("id")
			if id == "ALL" || id == "" {
				//var objs []mobj
				webapi.SendResult(nil, errors.New("sname is empty or all"), c)

			} else {
				err := dbconn.DBConnection.Delete(&MObj{
					SName: id,
				}).Error
				if err == nil {
					webapi.SendOK(c)
				} else {
					webapi.SendError(err.Error(), webapi.DBError, c)
				}
			}

		})
	}
}
